package com.topvision.camerasdk.camera2;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.topvision.camerasdk.R;
import com.topvision.camerasdk.album.MyAblumActivity;
import com.topvision.camerasdk.camera.CameraConstants;
import com.topvision.camerasdk.camera.SettingActivity;
import com.topvision.camerasdk.camera.TakePhotoCallback;
import com.topvision.camerasdk.camera.util.CameraUtil;
import com.topvision.camerasdk.camera.view.CameraView;
import com.topvision.camerasdk.video.util.VideoConstant;
import com.topvision.commomsdk.TouchInterface;
import com.topvision.commomsdk.uitl.AndroidUtils;
import com.topvision.commomsdk.uitl.FileUtil;
import com.topvision.commomsdk.uitl.PreferencesUtils;
import com.topvision.voicesdk.BaseVoiceActivity;
import com.topvision.voicesdk.CommonVoice;
import com.topvision.voicesdk.VoiceInterface;

import java.io.File;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * User: jack(jackgu@topvision-cv.com)
 * Date: 2016-11-21
 * Time: 10:30
 */
public class CameraActivity2 extends BaseVoiceActivity implements TouchInterface, VoiceInterface, View.OnClickListener {
    //默认拍照宽高
    public static final int DEFAULT_PICTURE_WIDTH = 1024;
    public static final int DEFAULT_PICTURE_HEIGHT = 768;
    public static final String THUMBNAIL_NAME = "thumbnail";
    //如果传过来的保存路径为空,则给默认拍照路径
    //  public static String TAKE_PHOTO_FOLDER = VideoConstant.photoFolderPath;


    //录像机视图
    CameraView cameraView;
    int currentId = 0;
    //存放控件集合
    ArrayList<Integer> viewIds;
    //一些按鈕控件
    ImageView takePictureIv, resolutionIv, backIv, albumIv;
    //相冊的背景
    View albumView;
    //通過indexSelected选择控件,默认选中为拍照
    int indexSelected = 1;
    Context context;
    TextView tips, voiceTips;
    //语音提示内容是否显示
    boolean voiceTipFlag = false;
    //文件保存路径目录
    String savePath;
    //拍照的前提必须是该字段为true
    public boolean isTakingPhoto = true;

    String msgSavePath;
    //打开闪光灯的阀值
    private final int OPEN_FLASH_VALUE = 50;
    private final int TAKE_PHOTO_TIME_VALUE = 5000;
    //当前灯光值
    float lightValue = 0;
    //记录拍照时间
    public static long takePicTime = 0;

    View focusIndex;
    public static CameraActivity2 mActivity;
    TakePhotoCallback takePhotoCallback;
    private CameraTextureView mCameraTextureView;
    boolean safeTakePhoto = true;
    Timer timer = new Timer();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_camera2);
        context = this;
        mActivity = this;
        //配置CameraTexture
        initUi();
        initData();
        //TvSdk.startVoiceTrack(context, TvSdk.DEFAULT_VOICE_MIN, TvSdk.DEFAULT_VOICE_TYPE);
       // timer.schedule(task, 5000, 300);

    }

    TimerTask task = new TimerTask() {
        public void run() {
//            takePhoto();
            hander.sendEmptyMessage(HANDLER_DO_CLICK);
//            doClickTouch();
        }
    };

    public final int HANDLER_DO_CLICK = 1;
    Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_DO_CLICK:
                    doClickTouch();
                    break;
            }
        }
    };

    private void initData() {
        currentId = R.id.take_picture_iv;
        viewIds = new ArrayList<>();
        viewIds.add(R.id.resolution_iv);
        viewIds.add(R.id.take_picture_iv);
        viewIds.add(R.id.back_iv);
        viewIds.add(R.id.album_iv);

        getMsg();
        savePath = getIntent().getStringExtra(CameraConstants.SAVE_PATH);
        voiceTipFlag = getIntent().getBooleanExtra(CameraConstants.VOICE_TIPS_FLAG, true);
        //换成用户传来的拍照地址路径
        if (!TextUtils.isEmpty(savePath)) {
            CameraConstants.TAKE_PHOTO_FOLDER = savePath;
        }
        //是否需要显示语音提示
        if (!voiceTipFlag) {
            voiceTips.setVisibility(View.GONE);
        }
        //换成用户传来的拍照地址路径
        if (!TextUtils.isEmpty(msgSavePath)) {
            CameraConstants.TAKE_PHOTO_FOLDER = msgSavePath;
        }
        //如果有外置sdcard,则保存在外置sdcard
        String extSdcard = AndroidUtils.getExtSDCardPath(context);
        if (!TextUtils.isEmpty(extSdcard)) {
            CameraConstants.TAKE_PHOTO_FOLDER = extSdcard + VideoConstant.PHOTO_FOLDER;
        } else {
            CameraConstants.TAKE_PHOTO_FOLDER = VideoConstant.photoFolderPath;
        }
        FileUtil.createFolder(getApplicationContext(), CameraConstants.TAKE_PHOTO_FOLDER);
    }

    /**
     * 获取清单文件中传过来的值 用于我们luancher上的 照相机
     * Get msg.
     */
    public void getMsg() {
        ActivityInfo info = null;
        try {
            info = this.getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Bundle metaData = info.metaData;
        if (metaData != null) {
            msgSavePath = metaData.getString("msgPhotoPath");
            System.out.println("msgPhotoPath:" + msgSavePath);
        }

    }


    private void initUi() {
        mCameraTextureView = (CameraTextureView) findViewById(R.id.texture);
        mCameraTextureView.setActivity(mActivity);
        takePictureIv = (ImageView) findViewById(R.id.take_picture_iv);
        resolutionIv = (ImageView) findViewById(R.id.resolution_iv);
        backIv = (ImageView) findViewById(R.id.back_iv);
        albumIv = (ImageView) findViewById(R.id.album_iv);
        albumView = findViewById(R.id.album_view);
        tips = (TextView) findViewById(R.id.tips);
        voiceTips = (TextView) findViewById(R.id.voice_tips);


        focusIndex = findViewById(R.id.focus_index);

        //如果是bt300，添加点击事件
        if (AndroidUtils.isBtDevice()) {
            registClickListener();
            currentMode = MODE_SWIPE;
        }
    }

    private void registClickListener() {
        takePictureIv.setOnClickListener(this);
        resolutionIv.setOnClickListener(this);
        backIv.setOnClickListener(this);
        albumIv.setOnClickListener(this);
    }

    private void unRegistClickListener() {
        takePictureIv.setOnClickListener(null);
        resolutionIv.setOnClickListener(null);
        backIv.setOnClickListener(null);
        albumIv.setOnClickListener(null);
    }


    long startTime;
    public int takeCount = 0;

    private void takePhoto() {

        if (!safeTakePhoto) {
            //  ToastUtils.showToast(getApplicationContext(),"拍照太快啦,请稍后");
            return;
        }

        startTime = System.currentTimeMillis();
        safeTakePhoto = false;
        mCameraTextureView.takePicture(new CameraTextureView.TackPhotoCallback() {
            @Override
            public void tackPhotoSuccess(String photoPath) {
                safeTakePhoto = true;
                Log.e("tvLog", "进行下一次拍照");
            }

            @Override
            public void tackPhotoError(Exception e) {
                ToastUtils.showToast(getApplicationContext(), e.getMessage());
                safeTakePhoto = true;
            }

            @Override
            public void takePhotoError2(String msg) {
                showToast(msg);
                safeTakePhoto = true;
            }

            @Override
            public void savePhotoSuccess(String photoPath) {
                Log.e("tvLog", "保存照片成功:" + photoPath);
                Log.e("tvLog", "take Count=" + takeCount++);
                Picasso.with(getApplicationContext())
                        .load("file://" + photoPath)
                        .config(Bitmap.Config.RGB_565)
                        .resize((int) getResources().getDimension(R.dimen.x80), (int) getResources().getDimension(R.dimen.x80))
                        .memoryPolicy(MemoryPolicy.NO_CACHE)
                        .centerCrop()
                        .into(albumIv);
            }
        });
    }

    private boolean ExistSDCard() {
        if (Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }

    }


    private Handler handler = new Handler();


    /**
     * 跳转到设置分辨率
     *
     * @author jack
     * create at 2016/11/22 17:37
     */
    private void forwardResolution() {
        Intent resolutionIntent = new Intent(CameraActivity2.this,
                SettingActivity.class);
        resolutionIntent.putExtra(CameraConstants.VOICE_TIPS_FLAG, voiceTipFlag);
        startActivity(resolutionIntent);
    }

    /**
     * 跳转到相册
     *
     * @author jack
     * create at 2016/11/22 17:37
     */
    private void forwardAlbum() {
        Intent myAlbumIntent = new Intent(CameraActivity2.this,
                MyAblumActivity.class);
        myAlbumIntent.putExtra(CameraConstants.VOICE_TIPS_FLAG, voiceTipFlag);
        myAlbumIntent.putExtra(VideoConstant.ABLUM_TYPE, VideoConstant.ABLUM_TYPE_PHOTO);/*** 12.13修改  ****/
        startActivity(myAlbumIntent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setTouchInterfaceListener(this);
        setVoiceInterfaceListener(this);
        mCameraTextureView.onResume();
        safeTakePhoto = true;
        if (AndroidUtils.isBtDevice()) {
            if (currentMode == MODE_BUTTON) {
                stateTag();
            } else {
                hideStateTag();
            }
        } else {
            stateTag();
        }
        setTips();
        //設置最新的相冊背景图
        new FileAsyncTask().execute(CameraConstants.TAKE_PHOTO_FOLDER);
        //registerSensor();
        //   startTask();
    }


    @Override
    protected void onPause() {
        super.onPause();
        setTouchInterfaceListener(this);
        setVoiceInterfaceListener(this);
        mCameraTextureView.onPause();
        safeTakePhoto = false;
        // unRegisterSensor();
        //  stopTask();
    }


    @Override
    public void doForwardTouch() {
        if (currentMode == MODE_BUTTON) {
            if (indexSelected < viewIds.size() - 1) {
                indexSelected++;
                currentId = viewIds.get(indexSelected);
                stateTag();
            }
        }
    }

    @Override
    public void doBackwardTouch() {
        if (currentMode == MODE_BUTTON) {
            if (indexSelected > 0) {
                indexSelected--;
                currentId = viewIds.get(indexSelected);
                stateTag();
            }
        }
    }

    @Override
    public void doClickTouch() {
        if (currentMode == MODE_BUTTON) {
           // ToastUtils.showToast(getApplicationContext(),"takephoto");
            if (currentId == R.id.take_picture_iv) {
                takePhoto();
            } else if (currentId == R.id.resolution_iv) {
                forwardResolution();
            } else if (currentId == R.id.back_iv) {
                finish();
            } else if (currentId == R.id.album_iv) {
                forwardAlbum();
            }
        }
    }

    private int currentMode = 0;//默认模式
    private static final int MODE_BUTTON = 0;//按钮模式
    private static final int MODE_SWIPE = 1;//BT300触摸模式

    @Override
    public void doDoubleTouch() {
        //切换模式
        if (AndroidUtils.isBtDevice()) {
            if (currentMode == MODE_BUTTON) {
                currentMode = MODE_SWIPE;
                registClickListener();
                hideStateTag();
            } else {
                currentMode = MODE_BUTTON;
                unRegistClickListener();
                stateTag();
            }
        } else {
            takePhoto();
        }
    }


    private void stateTag() {
        if (currentId == R.id.take_picture_iv) {
            takePictureIv.setImageResource(R.drawable.camera_selected);
            backIv.setImageResource(R.drawable.back_unselected);
            resolutionIv.setImageResource(R.drawable.resolution_unselected);
            albumView.setVisibility(View.GONE);
        } else if (currentId == R.id.resolution_iv) {
            takePictureIv.setImageResource(R.drawable.camera_unselected);
            backIv.setImageResource(R.drawable.back_unselected);
            resolutionIv.setImageResource(R.drawable.resolution_selected);
            albumView.setVisibility(View.GONE);
        } else if (currentId == R.id.back_iv) {
            takePictureIv.setImageResource(R.drawable.camera_unselected);
            backIv.setImageResource(R.drawable.back_selected);
            resolutionIv.setImageResource(R.drawable.resolution_unselected);
            albumView.setVisibility(View.GONE);
        } else if (currentId == R.id.album_iv) {
            takePictureIv.setImageResource(R.drawable.camera_unselected);
            backIv.setImageResource(R.drawable.back_unselected);
            resolutionIv.setImageResource(R.drawable.resolution_unselected);
            albumView.setVisibility(View.VISIBLE);
        }

    }

    private void hideStateTag() {
        if (currentId == R.id.take_picture_iv) {
            takePictureIv.setImageResource(R.drawable.camera_unselected);
            backIv.setImageResource(R.drawable.back_unselected);
            resolutionIv.setImageResource(R.drawable.resolution_unselected);
            albumView.setVisibility(View.GONE);
        } else if (currentId == R.id.resolution_iv) {
            takePictureIv.setImageResource(R.drawable.camera_unselected);
            backIv.setImageResource(R.drawable.back_unselected);
            resolutionIv.setImageResource(R.drawable.resolution_unselected);
            albumView.setVisibility(View.GONE);
        } else if (currentId == R.id.back_iv) {
            takePictureIv.setImageResource(R.drawable.camera_unselected);
            backIv.setImageResource(R.drawable.back_unselected);
            resolutionIv.setImageResource(R.drawable.resolution_unselected);
            albumView.setVisibility(View.GONE);
        } else if (currentId == R.id.album_iv) {
            takePictureIv.setImageResource(R.drawable.camera_unselected);
            backIv.setImageResource(R.drawable.back_unselected);
            resolutionIv.setImageResource(R.drawable.resolution_unselected);
            albumView.setVisibility(View.GONE);
        }

    }


    /**
     * 一些信息提示
     *
     * @author jack
     * create at 2016/11/21 11:55
     */
    private void setTips() {
        if (tips != null) {
            int width = PreferencesUtils.getInt(context, "wide", 1024);
            int high = PreferencesUtils.getInt(context, "high", 768);

            String strTips = getString(R.string.version_name) + AndroidUtils.getVersion(context) + "\n" + getString(R.string.resolution) + width + "x" + high;
            tips.setText(strTips);
        }
    }

    @Override
    public void dealWithVoice(String data) {
        data = data.toLowerCase();
        if (CommonVoice.VOICE_ZH_TAKE_PHOTO.equals(data) || CommonVoice.VOICE_US_TAKE_PHOTO.equalsIgnoreCase(data)) {
            takePhoto();
        } else if (CommonVoice.VOICE_ZH_BACK.equals(data) || CommonVoice.VOICE_US_BACK.equalsIgnoreCase(data)) {
            this.finish();
        } else if (CommonVoice.VOICE_ZH_UP.equals(data) || CommonVoice.VOICE_US_UP.equalsIgnoreCase(data)) {
            doBackwardTouch();
        } else if (CommonVoice.VOICE_ZH_DOWN.equals(data) || CommonVoice.VOICE_US_DOWN.equalsIgnoreCase(data)) {
            doForwardTouch();
        } else if (CommonVoice.VOICE_ZH_ALBUM.equals(data) || CommonVoice.VOICE_US_ALBUM.equalsIgnoreCase(data) || CommonVoice.VOICE_US_PHOTO.equalsIgnoreCase(data)) {
            forwardAlbum();
        } else if (CommonVoice.VOICE_ZH_SET.equals(data) || CommonVoice.VOICE_US_SET.equalsIgnoreCase(data)) {
            forwardResolution();
        } else if (CommonVoice.VOICE_ZH_OK.equals(data) || CommonVoice.VOICE_US_OK.equalsIgnoreCase(data) || CommonVoice.VOICE_US_CONFIRM.equalsIgnoreCase(data)) {
            doClickTouch();
        }
    }

    /**
     * BT300的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.take_picture_iv) {
            takePhoto();
        } else if (id == R.id.resolution_iv) {
            forwardResolution();
        } else if (id == R.id.back_iv) {
            finish();
        } else if (id == R.id.album_iv) {
            forwardAlbum();
        }
    }


    /**
     * 设置相册最新的背景图
     *
     * @author jack
     *         create at 2016/11/21 13:45
     */
    class FileAsyncTask extends AsyncTask<String, Void, File> {


        @Override
        protected File doInBackground(String... strings) {
            //获取拍照目录下最新的缩略图显示在相册上
            File file = CameraUtil.getNewestFile(CameraConstants.THUMBNAIL_FOLDER);
            return file;
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            if (file != null) {
                Picasso.with(context).load(file).error(R.mipmap.pic_fail).into(albumIv);
            } else {
                Picasso.with(context).load(R.mipmap.xiangce).error(R.mipmap.pic_fail).into(albumIv);
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        takePicTime = 0;
        if (takePhotoCallback != null && takePhotoCallback.getCurrPhoto() != null) {
            //释放图片资源
            takePhotoCallback.getCurrPhoto().recycle();
        }
    }


    SensorManager sensorManager = null;

    private void registerSensor() {
        //获取SensorManager对象
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        //获取Sensor对象
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    private void unRegisterSensor() {
        if (sensorManager != null) {
            sensorManager.unregisterListener(listener);
        }
    }


    SensorEventListener listener = new SensorEventListener() {

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            //当传感器精度发生变化时
        }

        private long registerTime = 0;

        @Override
        public void onSensorChanged(SensorEvent event) {

            if (registerTime == 0) {
                registerTime = System.currentTimeMillis();
            }
            if (System.currentTimeMillis() - registerTime < 3000) {
                return;
            }
            //当传感器监测到的数值发生变化时
            // values数组中第一个值就是当前的光照强度
            if (cameraView.getCameraInstance() == null || cameraView == null) {
                return;
            }
            lightValue = event.values[0];
            Log.e("lightValue", String.valueOf(lightValue));
            if (lightValue < OPEN_FLASH_VALUE) {
                //没打开则进行打开
                if (!cameraView.isFlashFlag()) {
                    cameraView.openFlashLight();
                }

            } else {
                //开过闪光灯则进行关闭
                if (cameraView.isFlashFlag()) {
                    cameraView.closeFlashLight();
                }
            }
        }
    };


    private final int HANDLER_CLOSE_FLASH = 1;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_CLOSE_FLASH:
                    if (cameraView != null && cameraView.isFlashFlag()) {
                        cameraView.closeFlashLight();
                    }
            }
        }
    };


    /**
     * 启动定时器,轮训查询未注册的人脸信息
     * 创建时间:2017/10/12
     * 作者 jack
     * 描述
     */
    private ScheduledExecutorService scheduledThreadPool;

    private void startTask() {
        scheduledThreadPool = Executors.newScheduledThreadPool(1);
        //scheduleAtFixedRate 会等command命令执行完后,才继续执行下一个command
        scheduledThreadPool.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                takePhoto();
            }
        }, 1, 50, TimeUnit.MILLISECONDS);
    }


    private void stopTask() {
        if (scheduledThreadPool != null && !scheduledThreadPool.isShutdown()) {
            scheduledThreadPool.shutdown();
            scheduledThreadPool = null;
        }
    }

    public boolean isTakingPhoto() {
        return isTakingPhoto;
    }

    public void setTakingPhoto(boolean takingPhoto) {
        isTakingPhoto = takingPhoto;
    }

    private void showToast(final String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }
}